<template>
  <div class="app-container">
    <el-tabs
        v-model="activeName"
        @tab-change="handleClick"
    >
      <el-tab-pane key="all" name="all">
        <template #label>
          <i class="el-icon-s-operation">
            <span>全部项目</span>
          </i>
        </template>
      </el-tab-pane>
      <el-tab-pane key="collect" name="collect">
        <template #label>
          <i class="el-icon-star-on">
            <span>我的收藏</span>
          </i>
        </template>
      </el-tab-pane>
      <el-tab-pane key="archive" name="archive">
        <template #label>
          <i class="el-icon-s-order">
            <span>已归档</span>
          </i>
        </template>
      </el-tab-pane>
    </el-tabs>


    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-input
              style="width: 200px;"
              v-model="queryParams.projectName"
              placeholder="请输入项目名称，回车搜索"
              clearable
              @keyup.enter="handleQuery"
          />
          <el-button
              type="primary"
              style="float: right;"
              @click="handleAdd"
          >
            <Icon icon="ep:plus" class="mr-5px"/>
            创建新项目
          </el-button>
        </div>
      </template>


      <div v-for="(item, index) in list" :key="index">
        <el-row :gutter="20">
          <el-col :span="16">
            <div style="display: flex; align-items: center; justify-content: flex-start;">
              <image-preview :src="item.projectImg" width="80px" height="80px"/>
              <div style="margin-left: 10px;">
                <el-link @click="() => handleOpen(item)" type="primary" style="font-size: 18px;">
                  {{ item.projectName }}
                </el-link>
                <span style="font-size: 14px; color: #C0C4CC;">{{ item.remark }}</span>
              </div>
            </div>
          </el-col>

          <el-col :span="4">
            <span>
            {{ item.creator_dictText + "-" }}
            </span>
            <span>
            {{ formatDate(item.createTime, 'YYYY-MM-DD') }}
            </span>
          </el-col>

          <el-col :span="4" class="flex items-center gap-1">
            <el-tooltip content="新增任务" placement="top">
              <el-button
                  type="text"
                  @click="handleOpen(item)"
              >
                <Icon icon="ep:plus" class="mr-5px"/>
              </el-button>
            </el-tooltip>

            <el-divider direction="vertical"/>

            <el-tooltip content="修改" placement="top">
              <el-button
                  type="text"
                  @click="handleUpdate(item)"
              >
                <Icon icon="ep:edit" class="mr-5px"/>
              </el-button>
            </el-tooltip>

            <el-divider direction="vertical"/>

            <el-tooltip content="收藏" placement="top">
              <el-text

                  @click="handleCollect(item)"
              >
                <Icon :icon="getIsCollect(item)?'ep:star-filled':'ep:star'"
                      :color="getIsCollect(item) ? '#409eff' : ''"/>
              </el-text>
            </el-tooltip>

            <el-divider direction="vertical"/>

            <el-tooltip v-if="activeName !== 'archive'" content="归档" placement="top">
              <el-button
                  type="text"
                  @click="handleArchive(item)"
              >
                <Icon icon="ep:document" class="mr-5px"/>
              </el-button>
            </el-tooltip>
          </el-col>

        </el-row>
        <el-divider/>
      </div>

    </el-card>

    <!-- 添加或修改部门协同-项目列对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目模板" prop="templateId">
          <el-select v-model="form.templateId" placeholder="请选择" filterable
                     @change="templateChange">
            <el-option
                v-for="item in templateList"
                :key="item.id"
                :label="item.templateName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目图片" prop="templateImg">
          <upload-img v-model="form.projectImg"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="项目简介" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {ProjectListApi} from '@/api/business/synergy/project/list'
import {ProjectTemplateApi} from '@/api/business/synergy/project/template'
import {formatDate} from "@/utils/formatTime";
import {useUserStore} from "@/store/modules/user";

const {push} = useRouter()

const userStore = useUserStore()
const message = useMessage() // 消息弹窗
// 响应式数据
const activeName = ref('all')
const loading = ref(true)
const total = ref(0)
const list = ref([])
const templateList = ref([])
const title = ref('')
const open = ref(false)
const formRef = ref(null)

// 查询参数
const queryParams = ref({
  templateId: null,
  projectName: null,
  projectCollect: null,
  state: null
})

// 表单数据
const form = ref({
  id: null,
  templateId: null,
  projectName: null,
  projectImg: null,
  projectFile: null,
  projectCollect: null,
  projectUsers: null,
  state: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  remark: null
})

// 表单校验规则
const rules = ref({
  projectName: [
    {required: true, message: '项目名称不能为空', trigger: 'blur'}
  ],
  templateId: [
    {required: true, message: '项目模板不能为空', trigger: 'blur'}
  ]
})

// 生命周期 - 挂载完成
onMounted(() => {
  getListData()
  getListTemplate()
})

// 获取模板列表
const getListTemplate = async () => {
  const data = await ProjectTemplateApi.getProjectTemplatePage();
  templateList.value = data.list
}

// 查询部门协同-项目列列表
const getListData = async () => {
  loading.value = true
  queryParams.value.state = activeName.value
  try {
    const data = await ProjectListApi.getProjectListPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    templateId: null,
    projectName: null,
    projectImg: null,
    projectFile: null,
    projectCollect: null,
    projectUsers: null,
    state: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleted: null,
    remark: null
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getListData()
}


// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加部协同项目'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  if (userStore.user.id.toString()!='1'&&userStore.user.id.toString() !== row.creator) {
    message.error('您没有权限！')
    return
  }
  reset()
  form.value = await ProjectListApi.getProjectList(row.id)
  open.value = true
  title.value = '修改协同项目'
}

// 提交按钮
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (form.value.id !== null) {
    await ProjectListApi.updateProjectList(form.value)
    message.success('修改成功')
    open.value = false
    await getListData()
  } else {
    await ProjectListApi.createProjectList(form.value)
    message.success('新增成功')
    open.value = false
    await getListData()
  }
}

// 归档按钮操作
const handleArchive = async (row) => {
  if (userStore.user.id.toString()!='1'&& userStore.user.id.toString() !== row.creator) {
    message.error('您没有权限！')
    return
  }
  await message.delConfirm(`是否确认归档协同项目名称为"${row.projectName}"的数据项？`)
  let archiveForm = {
    id: row.id,
    state: '归档'
  }
  await ProjectListApi.updateProjectList(archiveForm)
  message.success('归档成功')
  await getListData()
}

// 收藏按钮操作
const handleCollect = async (row) => {
  await ProjectListApi.collectProject({id: row.id})
  message.success('操作成功')
  await getListData()
}


// 标签切换
const handleClick = (tab) => {
  activeName.value = tab
  getListData()
}

// 打开任务列表
const handleOpen = (row) => {
  let id = row.id
  push({name: 'SynergyProjectTaskList', params: {id}})
}

// 模板变更
const templateChange = () => {
  const template = templateList.value.find(item => item.id === form.value.templateId)
  if (template && template.templateImg) {
    form.value.projectImg = template.templateImg
  }
}

const getIsCollect = (item) => {
  let flag = false
  if (!item.projectCollect) {
    return flag
  }
  item.projectCollect.split(',').forEach(i => {
    if (i == userStore.user.id.toString()) {
      flag = true
      return flag
    }
  })
  return flag
}
</script>
